package com.zhangxin.aiInterview.manager.work_flow.tts_boy;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 简历内容提取智能体
 */
public class TTsBoy {

    // 替换为你的API Key 和 API Secret
    private static final String API_KEY = "cd5245ddf5444cfcedd25b57a29b4c0b";
    private static final String API_SECRET = "MzdhNDEzNzVkMDcyZDhhZTM3MWNjODhj";
    private static final String FLOW_ID = "7321730287100755970";  // 工作流 ID

    public static void main(String[] args) {
        String s = generateAudio("Here’s a generated English audio clip for you. Since I can’t directly create audio files, I’ll provide a script that you can use with a \u200B\u200Btext-to-speech (TTS)\u200B\u200B tool like Google Text-to-Speech, Amazon Polly, or OpenAI's TTS API.\n" +
                "Script for Audio (Clear & Natural English):\n" +
                "The 'volatile' keyword in Java ensures visibility and ordering in multithreaded environments. When a variable is declared volatile, any write to it is immediately visible to other threads. Additionally, the JVM prevents reordering of instructions around volatile operations. However, volatile does not guarantee atomicity—for complex operations, use synchronized blocks or atomic classes. A common use case is a status flag shared between threads.");
        System.out.println(s);
    }

    /**
     * 简历内容提取
     *
     * @param text 简历路径
     */
    public static String generateAudio(String text) {

        StringBuilder result = new StringBuilder();
        try {
            // 1. 构建请求体 JSON（使用 Hutool）
            JSONObject parameters = new JSONObject();
            parameters.put("AGENT_USER_INPUT", text);

            JSONObject requestBody = new JSONObject();
            requestBody.put("flow_id", FLOW_ID);
            requestBody.put("uid", "123");
            requestBody.put("stream", true);
            requestBody.put("parameters", parameters);

            // 2. 构建请求 URL
            URL url = new URL("https://xingchen-api.xf-yun.com/workflow/v1/chat/completions");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法和头部
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            // 设置 Authorization
            String authorizationHeader = "Bearer " + API_KEY + ":" + API_SECRET;
            connection.setRequestProperty("Authorization", authorizationHeader);
            connection.setDoOutput(true);
            // 4. 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input);
            }
            // 5. 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        result.append(line);
                    }
                    System.out.println(result);
                    String json = result.toString().replace("data: ", "");
                    JSONObject jsonObject = JSONUtil.parseObj(json);
                    JSONArray choices = jsonObject.getJSONArray("choices");
                    JSONObject firstChoice = choices.getJSONObject(0);
                    JSONObject delta = firstChoice.getJSONObject("delta");
                    // 4. 提取content字段中的URL
                    return delta.getStr("content");
                }
            } else {
                System.out.println("Error: HTTP " + responseCode);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    System.out.println("Error Response: " + errorResponse);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
